
import Dialog from "@vant/weapp/dialog/dialog";
const app = getApp();
const { AskPage } = app._require('common/index');
const formMixin = app._require("mixins/form.mixin.js").default;
const { taskStateList } = app._require("pages/task/mixin.js");
import { nodeData } from "./mock.js";
AskPage({
    /**
     * 页面的初始数据
     */
    name: "taskForm",
    mixins: [formMixin],
    data: {
        nodeData: nodeData,
        keyMap: [],
        validate: [],
        model: {
            executor: "",
            taskId: "",
            shareId: "",
            makePhone: "",
            id: "",
            title: "",
            readonly: true,
            line: 0,
            description: "",
        },
    },
    onLoad(options) {
        let { shareId, taskId, sharePhone, line, id } = options;
        this.setData({
            "model.taskId": taskId || "",
            "model.id": id || "",
            "model.shareId": shareId || "",
            "model.makePhone": sharePhone || "",
            "model.line": line || 0,
        });
        console.log(options);
        this.setUploadDir();
        this.initForm();
    },
    loginSuccess() {
        this.initForm();
    },
    async initForm() {
        let model = {};
        if (this.data.model.id) {
            model = await this.initData();
        }
        this.initDimensionData(model);
    },
    onSelectClick(e) {
        let { key } = e.currentTarget.dataset;
        let { value: item } = e.detail;
        let _value = this.data.model[key] || "";
        if (_value === item.value) {
            _value = "";
        } else {
            _value = item.value;
        }
        // this.selectComponent("#sortDrop").toggle();
        this.setData({
            ["model." + key]: _value,
        });
    },
    onCascaderClick(e) {
        let { key } = e.currentTarget.dataset;
        let { value: item } = e.detail;
        let _key = "model." + key;
        let values = this.data.model[key] || [];
        let _index = values.findIndex(cur => cur === item.value);
        if (_index === -1) {
            values.push(item.value);
        } else {
            values.splice(_index, 1);
        }
        this.setData({
            [_key]: values,
        });
    },
    locationChange(e) {
        console.log("e", e);
        const { key: sKey } = e.currentTarget.dataset;
        const { key } = e.detail.currentTarget.dataset;
        const { value } = e.detail.detail;
        let _key = "";
        if (key === "address") {
            _key = sKey;
        } else {
            _key = key.replace("address", sKey);
        }
        this.setModel({
            currentTarget: {
                dataset: {
                    key: _key,
                },
            },
            detail: {
                value,
            },
        });
    },
    onTextAreaChange(e) {
        const { key: sKey } = e.currentTarget.dataset;
        const value = e.detail;
        this.setModel({
            currentTarget: {
                dataset: {
                    key: sKey,
                },
            },
            detail: {
                value: value,
            },
        });
    },
    callPhone() {
        wx.makePhoneCall({
            phoneNumber: this.data.model.makePhone || "4008618890", //仅为示例，并非真实的电话号码
        });
    },
    async initData() {
        try {
            let { id } = this.data.model;
            const response = await this.$_server("taskFill/query", {
                params: {
                    id: id,
                },
            });
            let { data } = response;
            if (data.code !== 200) {
                throw data;
            }
            let { data: list } = data;
            let model = {};
            let dimensionList = list.dimensionalityDataVoList || [];
            for (let i = 0; i < dimensionList.length; i++) {
                const cur = dimensionList[i];
                if (cur.dimensionalityId) {
                    model[cur.dimensionalityId] = cur.value;
                }
            }
            this.setData({
                "model.executor": (list.executor || "") + "",
            });
            return model;
        } catch (error) {
            console.log(error);
            // statements
            if (error.msg) {
                wx.showToast({
                    mask: true,
                    title: error.msg,
                    icon: "none",
                    duration: 2000,
                });
            } else {
                throw error;
            }
        }
    },
    async initDimensionData(dataResponse = {}) {
        try {
            let { taskId } = this.data.model;
            const response = await this.$_server("taskFill/dimension", {
                params: {
                    id: taskId,
                },
            });
            let { data } = response;
            if (data.code !== 200) {
                throw data;
            }
            let { data: list } = data;

            const keyMap = [];
            const validate = [];
            let state = this.$key2Name(
                {
                    type: list.taskStatus + "",
                    key: "state",
                    list: taskStateList,
                },
                "obj"
            );
            const model = {
                title: list.templateName || "",
                description: list.description || "",
                makePhone: this.data.model.makePhone || list.telephone || "",
                readonly: !!list.readonly,
            };
            if (!model.readonly) {
                model.readonly = state.value !== "EXECUTING";
            }
            // this.data.nodeData.forEach((cur, index) => {
            //     keyMap.push({
            //         ...cur,
            //         _key: index,
            //     });
            //     if (cur.type !== "deadline") {
            //         if (cur.type === "location") {
            //             model[cur.key] = {
            //                 cityCode: "", // 城市的code
            //                 latitude: "", // 纬度
            //                 longitude: "", // 经度
            //                 info: "", // 详细地址
            //             };
            //         } else {
            //             model[cur.key] = cur.value;
            //         }
            //         if (cur.option && cur.option.rules && cur.option.rules.length > 0) {
            //             validate.push([cur.key, cur.option.rules]);
            //         }
            //     }
            // });
            let dimensionList = list.templateDimensionalityVoList || [];
            let resourceUrl = this.data.$_config.url;
            for (let i = 0; i < dimensionList.length; i++) {
                const cur = dimensionList[i];
                const _typeMap = this.formatTextToArray(cur.valueLabel, "-");
                const _dimensionId = cur.id || "";
                const _cur = {
                    // 属性名称
                    name: cur.name || "",
                    keyId: _dimensionId,
                    key: _typeMap[0] + i,
                    value: dataResponse[_dimensionId] || "",
                };
                model[_cur.key] = _cur.value;
                // cur.isFilling = true;
                if (_typeMap[0] === "input") {
                    _cur.type = _typeMap[0];
                    let _type = "";
                    let _placeholder = cur.placeholder || "请输入" + (cur.name || "");
                    let _class = "";
                    if (_typeMap[1] === "date") {
                        _type = "date";
                        _placeholder = cur.placeholder || "请选择" + (cur.name || "");
                        model[_cur.key] = _cur.value ? +new Date(_cur.value) : "";
                    } else if (_typeMap[1] === "textarea") {
                        _type = "textarea";
                        _class = "c-textarea";
                    } else {
                        _type = [("num", "phone")].includes(_typeMap[1]) ? "number" : "text";
                    }
                    _cur.option = {
                        type: _type,
                        placeholder: _placeholder,
                        class: _class,
                        labelClass: cur.isFilling ? "required" : "",
                        suffix: cur.unitKindName || "",
                        rules: this.formatTextToArray(cur.rules),
                    };
                    if (["email", "num", "phone", "alpha"].includes(_typeMap[1])) {
                        // if (["alpha"].includes(_typeMap[1])) {
                        _cur.option.rules.push(_typeMap[1]);
                    }
                }
                if (_typeMap[0] === "select" || _typeMap[0] === "cascader") {
                    _cur.type = "select";
                    _cur.option = {
                        type: _typeMap[0],
                        placeholder: cur.placeholder || "请选择" + (cur.name || ""),
                        class: "",
                        labelClass: cur.isFilling ? "required" : "",
                        suffix: cur.unitKindName || "",
                        rules: this.formatTextToArray(cur.rules),
                        list: (cur.optionIds || []).map(subCur => {
                            // subCur.name += +new Date() + "我是选项爱上大叔我打打我打我打我打打我打我打我打"
                            return {
                                label: subCur.name || "",
                                value: subCur.id || "",
                            };
                        }),
                    };
                    if (_typeMap[0] === "cascader") {
                        model[_cur.key] = this.formatTextToArray(_cur.value);
                    }
                }
                if (_typeMap[0] === "upload") {
                    _cur.type = "upload";
                    _cur.option = {
                        type: _typeMap[1] === "img" ? "image" : _typeMap[1],
                        class: "",
                        labelClass: cur.isFilling ? "required" : "",
                        rules: this.formatTextToArray(cur.rules),
                    };
                    if (_typeMap[1] === "record") {
                        model[_cur.key] = this.addImageUrlHost(_cur.value);
                    } else {
                        let _photos = this.formatTextToArray(_cur.value).map(cur => {
                            return { src: resourceUrl + cur, fileName: cur.replace(/^\//, "") };
                        });
                        model[_cur.key] = _photos;
                    }
                }
                if (_typeMap[0] === "location") {
                    _cur.type = "location";
                    _cur.option = {
                        class: "",
                        labelClass: cur.isFilling ? "required" : "",
                        rules: this.formatTextToArray(cur.rules),
                    };
                    let city = this.formatTextToArray(_cur.value);
                    model[_cur.key] = {
                        cityCode: city[0] || "", // 城市的code
                        cityInfo: city[1] || "", // 城市的cityInfo
                        longitude: city[4] || "", // 经度
                        latitude: city[3] || "", // 纬度
                        info: city[2] || "", // 详细地址
                    };
                }
                if (cur.isFilling) {
                    _cur.option.rules.unshift("required");
                }
                if (_cur.option && _cur.option.rules && _cur.option.rules.length > 0) {
                    validate.push(_cur);
                }
                keyMap.push(_cur);
            }
            // console.log("keyMap", keyMap);
            this.setData({
                keyMap,
                validate,
                model: {
                    ...this.data.model,
                    ...model,
                },
            });
        } catch (error) {
            console.log(error);
            // statements
            if (error.msg) {
                wx.showToast({
                    mask: true,
                    title: error.msg,
                    icon: "none",
                    duration: 2000,
                });
            } else {
                throw error;
            }
        }
    },
    async sure(e) {
        let { validate, model } = this.data;
        const ruleMsg = {
            email: "只能输入邮箱号!",
            num: "只能输入数字!",
            phone: "的格式不对!",
            alpha: "只能输入字母!",
        };
        const _v = validate.map(cur => {
            let { rules, placeholder, type } = cur.option;
        
            rules.forEach(rule => {
                if (rule === "required") {
                    if (cur.type === "location") {
                        _rule[rule] = "请选择" + cur.name;
                    } else if (cur.type === "upload") {
                        _rule[rule] = "请上传" + cur.name;
                    } else {
                        _rule[rule] = placeholder;
                    }
                } else {
                    _rule[rule] = ruleMsg[rule] ? cur.name + ruleMsg[rule] : "";
                }
            });
            const _cur = [];
            if (cur.type === "location") {
                _cur[0] = model[cur.key].cityCode;
            } else {
                _cur[0] = model[cur.key];
            }
            _cur[1] = _rule;
            return _cur;
        });
        let res = this.validateFiled(_v);
        if (!res.result) {
            wx.showToast({
                title: res.msg,
                icon: "none",
            });
            return false;
        }
        this.saveInfo();
    },
    async saveInfo() {
        let params = {};
        let list = [];
        let { model, keyMap } = this.data;
        for (let i = 0; i < keyMap.length; i++) {
            const cur = keyMap[i];
            const _cur = {
                dimensionalityId: cur.keyId,
                value: model[cur.key],
            };
            if (cur.type === "input" && cur.option.type === "date") {
                _cur.value = model[cur.key] ? new Date(model[cur.key]).format("yyyy-MM-dd") : "";
            }
            if (cur.type === "location") {
                if (model[cur.key].cityCode) {
                    _cur.value = model[cur.key].cityCode;
                    _cur.value += "," + model[cur.key].cityInfo;
                    _cur.value += "," + model[cur.key].info;
                    _cur.value += "," + model[cur.key].latitude;
                    _cur.value += "," + model[cur.key].longitude;
                } else {
                    _cur.value = "";
                }
            }
            if (cur.type === "select" && cur.option.type === "cascader") {
                _cur.value = model[cur.key].join(",");
            }
            if (cur.type === "upload") {
                if (cur.option.type === "record") {
                    _cur.value = this.removeImageUrlHost(model[cur.key]);
                } else {
                    let _photos = model[cur.key]
                        .filter(cur => !cur.status || cur.status === "success")
                        .map(cur => "/" + cur.fileName);
                    _cur.value = _photos.join(",");
                }
            }
            list.push(_cur);
        }
        const userInfo = (app.user && app.user.userInfo) || {};
        params = {
            dimensionalityDataVoList: list,
            taskId: model.taskId || "",
            executor: (model.executor || model.shareId || userInfo.id || "") + "",
        };
        let url = "task/add";
        if (model.id !== "") {
            params.id = model.id;
            url = "task/update";
        }
        // if (model.shareId !== "") {
        //     params.sender = model.shareId;
        // }
        console.log(params);
        try {
            const response = await this.$_server(url, {
                data: params,
            });
            let { data } = response;
            if (data.code !== 200) {
                throw data;
            }
            if (this.data.model.id === "") {
                this.confirm();
            } else {
                wx.askShowToastEx({
                    mask: true,
                    title: data.msg || "保存成功！",
                    duration: 2000,
                    icon: "none",
                    cancel: () => {
                        this.goBack();
                    },
                });
            }
        } catch (error) {
            console.log(error);
            // statements
            if (error.message) {
                wx.showToast({
                    mask: true,
                    title: error.message,
                    icon: "none",
                    duration: 2000,
                });
            } else {
                throw error;
            }
        }
    },
    goBack(callback) {
        wx.navigateBack({
            complete: () => {
                callback && callback();
            },
        });
    },
    loginSuccess() {
        this.initData();
    },
    confirm() {
        const beforeClose = action =>
            new Promise(resolve => {
                setTimeout(() => {
                    if (action === "confirm") {
                        this.setData({
                            "model.line": Number(this.data.model.line) + 1,
                        });
                        this.initForm().then(() => {
                            resolve(true);
                        });
                    } else {
                        this.goBack();
                        resolve(true);
                    }
                }, 100);
            });

        Dialog.confirm({
            title: "提示",
            message: "是否继续填写下一条？",
            beforeClose,
        });
    },
});
